import React from 'react';
import { Form, TreeSelect } from 'antd';
import type { ProFormItemProps } from '@ant-design/pro-form';
import type { TreeSelectProps } from 'antd';
import { useRequest } from 'umi';
import { getProviderApiTree } from '@/services/channel/sp_api';

interface ProFormTreeSelectProps extends ProFormItemProps {
  onlyLeafSelectable?: boolean;
  multiple?: boolean;
  fieldNames?: { label?: string; value?: string; children?: string };
  showSearch?: boolean;
  placeholder?: string;
  defaultExpandAll?: boolean;
}
interface SelectedNode {
  id: string;
  parentChain: string[];
  path?: string;
}
const ProFormTreeSelect: React.FC<ProFormTreeSelectProps> = ({
  label,
  name,
  rules,
  onlyLeafSelectable = true,
  multiple = false,
  fieldNames = { label: 'path', value: 'id', children: 'children' },
  showSearch = true,
  placeholder,
  defaultExpandAll = true,
  ...restProps
}) => {
  // 使用服务端接口
  const { data, loading } = useRequest(getProviderApiTree, {
    formatResult: (res) => res.data, // 直接取data字段    
  });

  // 处理树形数据
  const treeData = React.useMemo(() => {
    if (!data) return [];

    const processNode = (node: TreeNode): TreeNode => {
      const disabled = onlyLeafSelectable ? !node.isLeaf : false;
      return {
        ...node,
        disabled,
        children: node.children?.map(processNode),
      };
    };

    return data.map(processNode);
  }, [data, onlyLeafSelectable]);


  // 搜索过滤
  const filterTreeNode: TreeSelectProps['filterTreeNode'] = (input, node) => {
    const labelKey = fieldNames?.label || 'title';   
    return node![labelKey]?.toString().toLowerCase().includes(input.toLowerCase());
  };
  const { nodeMap, pathMap } = React.useMemo(() => {
    const nodeMap = new Map<string, TreeNode>();
    const pathMap = new Map<string, string>();

    const traverse = (node: TreeNode, parentPath?: string) => {
      const currentPath = parentPath
        ? `${parentPath}/${node.title}`
        : node.title;

      nodeMap.set(node.id, node);
      pathMap.set(node.id, currentPath);

      if (node.children) {
        node.children.forEach(child => traverse(child, currentPath));
      }
    };

    data?.forEach(node => traverse(node));
    return { nodeMap, pathMap };
  }, [data]);

  // const transformValue = (id: string) => {
  //   if (!id) return undefined;
  //   const node = nodeMap.get(id);
  //   return {
  //     id,
  //     parentChain: node?.parentChain || [],
  //     path: pathMap.get(id)
  //   };
  // };
  return (
    <Form.Item
      label={label}
      name={name}
      rules={rules}

      shouldUpdate={(prev, curr) => prev[name] !== curr[name]}
    >
      <TreeSelect
        treeData={treeData}
        loading={loading}
        treeCheckable={multiple}
        showSearch={showSearch}
        filterTreeNode={filterTreeNode}
        placeholder={placeholder || `请选择${label}`}
        fieldNames={fieldNames}
        allowClear
        treeDefaultExpandAll={defaultExpandAll}
        virtual
        {...restProps}
      />
    </Form.Item>
  );
};

export default ProFormTreeSelect;